import { remove } from '../util/index'

/**
 * 依赖收集，用来管理Watcher
 */
class Dep {
  constructor () {
    this.subs = [] // 存放所有依赖（watcher）
  }

  addSub (sub) {
    this.subs.push(sub)
  }

  /* 删除一个依赖 */
  removeSub (sub) {
    remove(this.subs, sub)
  }

  /* 添加一个依赖 */
  depend () {
    if (Dep.target) {
      Dep.target.addDep(this)
    }
  }

  /* 通知所有依赖更新 */
  notify () {
    for (let i = 0, l = this.subs.length; i < l; i++) {
      this.subs[i].update()
    }
  }
}

Dep.target = null
const targetStack = []

export function pushTarget (target) {
  targetStack.push(target)
  Dep.target = target
}

export function popTarget () {
  targetStack.pop()
  Dep.target = targetStack[targetStack.length - 1]
}

export default Dep
